import { login, getProfile } from '@/api/user'
import { setToken, getToken } from '@/utils/auth'
import { resetRouter } from '@/router/index'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    getUserInfo(state, newInfo) {
      state.userInfo = newInfo
    }
  },
  actions: {
    async login(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res.data)
      Message.success('登录成功')
    },
    async getProfile(context) {
      const res = await getProfile()
      context.commit('getUserInfo', res.data)
      return res
    },
    logout(context) {
      context.commit('setToken', '')
      context.commit('getUserInfo', {})
      resetRouter()
    }
  }
}
